package pt.ipleiria.estg.es2.byinvitationonly;

import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.preference.PreferenceManager;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;

import com.robotium.solo.Solo;

import pt.ipleiria.estg.es2.byinvitationonly.modelo.Contacto;

/**
 * Created by EduardoPortatil on 06-03-2015.
 */
public class MainActivityTestCase extends ActivityInstrumentationTestCase2<MainActivity> {

    private Solo solo;

    public MainActivityTestCase(){
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception{
        super.setUp();
        solo = new Solo(getInstrumentation(), getActivity());
        solo.unlockScreen();
    }

    @Override
    protected void tearDown() throws Exception{
        super.tearDown();
        solo.finishOpenedActivities();
    }

    public void testJanelaConfirmacao(){
        colocarContactoUser(new Contacto("Nome Exemplo", "mail@exemplo.com"));
        abrirJanelaDeConfirmacao();
        boolean apareceu = solo.waitForText(getActivity().getResources().getString(R.string.confirmacao), 1, 5000);
        assertTrue("A mensagem de confirmacao nao apareceu ", apareceu);
    }

    public void testConfirmarSubmit(){
        abrirJanelaDeConfirmacao();
        solo.clickOnButton(getActivity().getString(R.string.general_yes));

        boolean mudouActividade=solo.waitForActivity(WhoIsHereActivity.class, 5000);
        assertTrue("Nao mudou de actividade", mudouActividade);

        assertTrue("Icon nao apareceu", solo.waitForView(R.id.action_im_here));

        //Garantir que botão mudou
        TextView tv = (TextView) solo.getCurrentActivity().findViewById(R.id.action_im_here);
        BitmapDrawable icon = (BitmapDrawable) tv.getCompoundDrawables()[0];
        BitmapDrawable esperado = (BitmapDrawable) solo.getCurrentActivity().getDrawable(R.drawable.ic_action_together);

        boolean iguais = esperado.getBitmap().sameAs(icon.getBitmap());
    }

    private void abrirJanelaDeConfirmacao() {
        solo.clickOnActionBarItem(R.id.action_im_here);
    }

    private void colocarContactoUser(Contacto contacto) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(solo.getCurrentActivity());
        SharedPreferences.Editor editor = prefs.edit();

        editor.putString(solo.getString(R.string.pref_name), contacto.getNome());
        editor.putString(solo.getString(R.string.pref_email), contacto.getEmail());

        editor.commit();
    }

}
